import static org.apache.commons.lang.StringUtils.*
import org.codehaus.groovy.runtime.InvokerHelper
import org.codehaus.groovy.grails.commons.GrailsDomainClass

class RestController {

    private GrailsDomainClass domainClass
    private String domainClassName

    private String ok = "ok"
    private String error = "error"

    def beforeInterceptor = {
        domainClassName = capitalize(params.domain)
        domainClass = grailsApplication.getArtefact("Domain", domainClassName)
    }

    private invoke(method, parameters) {
        InvokerHelper.invokeStaticMethod(domainClass.getClazz(), method, parameters)
    }

    private format(obj) {
        if(params.format.equals("xml"))
            render(text:obj."encodeAsXML"(),contentType:"text/xml",encoding:"UTF-8")
        else
            render(text:obj."encodeAsJSON"())
    }

    def show = {
        def result
        if(params.id) result = [status:ok, content:invoke("get",params.id)]
        else result = [status:error, content:"${domainClassName} nao encontrada com identificado ${params.id}"]
        format(result)
    }

    def list = {
        def result
        if(!params.max) params.max = 10
        result = [status:ok, content:invoke("list", params)]
        format(result)
    }

    def delete = {
        def result = [status:ok, content:invoke("get", params.id)]
        if(result) result.delete()
        else result = [status:error, content:"${domainClassName} nao encontrada com identificado ${params.id}"]
        format(result)
    }

    def update = {
        def result
        def domain = result = [status:ok, content:invoke("get", params.id)]
        if(domain) {
            domain.properties = params
            if(!domain.hasErrors() && domain.save()) result = domain
            else result = [status:error, content:"${domainClassName} nao pode ser salvo"]
        } else result = [status:error, content:"${domainClassName} nao encontrada com identificado ${params.id}"]
    }

    def create = {
        def result
        def domain = InvokerHelper.invokeConstructorOf(domainClass.getClazz(), null)

        def input = ""
        request.inputStream.eachLine {
            input += it
        }
        if(input && input != '') {
            input.tokenize('&').each {
                def nvp = it.tokenize('=');
                params.put(nvp[0],nvp[1]);
            }
        }
        domain.properties = params

        if(!domain.hasErrors() && domainSave()) {
            result = [status:ok, content:domain]
        }else {
            result = [status:error, content: "${domainClassName} não pode ser criada"]
        }
        format(result)
    }
}
